import Snake from "./snake";
import Food from "./food";
import ScorePanel from "./scorePanel";

//游戏控制器 控制其他的类
class GameControl{
    snake:Snake;
    food:Food;
    score:ScorePanel;
    //创建一个属性来存储蛇的移动方向
    direction:string = '';
    //创建一个属性来储存游戏是否结束
    isLive = true;
    constructor(){
        this.snake = new Snake();
        this.food = new Food();
        this.score = new ScorePanel();
        this.init()
    }

    //游戏的初始化方法，调用后游戏开始
    init(){
        //按键绑定
        document.addEventListener('keydown',this.keydownHandler.bind(this));
        //调用run方法使蛇移动
        this.run();
    }
    //创建一个键盘按下的响应函数
    keydownHandler(event:KeyboardEvent){
        //检查event.key值是否合法
        //修改direction属性
        this.direction = event.key;
    }
    //创建一个控制蛇移动的方法
     run(){
        //根据方向使蛇的位置改变
        //获取现在蛇的位置
        let X = this.snake.X;
        let Y = this.snake.Y;
        //根据按键方向修改X和Y值
         switch (this.direction) {
             case "ArrowUp":
            //向上移动top减少
                Y-=10;
                 break;
             case "ArrowDown":
                Y+=10;
                 break;
             case "ArrowLeft":
                X-=10;
                 break;
             case "ArrowRight":
                X+=10;
                 break;

             default:
                 break;
         }

        //为蛇赋值
        try {
            this.snake.X = X;
            this.snake.Y = Y;
        } catch (e:any) {
            //捕获异常
            alert(e.message + '游戏结束！');
            this.isLive = false;
        }
        this.checkEat(X,Y);

        //开启定时调用
        this.isLive&&setTimeout(this.run.bind(this),400-(this.score.level-1)*30);
    }
    //定义检查蛇是否吃到食物
    checkEat(X:number,Y:number){
        if ( X === this.food.X&&Y === this.food.Y) {
             //食物位置重置
             this.food.change();
             //分数增加
             this.score.addSore();
             //蛇要加一节
             this.snake.addBody();
        }   
    }    
}

export default GameControl;